﻿// MyGL.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;


#include "Renderer.h"
#include "VertexArray.h"
#include "VertexBuffer.h"
#include "IndexBuffer.h"
#include "VertexBufferLayout.h"
#include "Shader.h"
#include "Texture.h"

#include <glm/glm.hpp>
#include <glm/ext.hpp>

#include "imgui/imgui.h"
#include "imgui/imgui_impl_glfw.h"
#include "imgui/imgui_impl_opengl3.h"

VertexArray* pVa = nullptr;
VertexBuffer* pVb = nullptr;
IndexBuffer* pIB = nullptr;
unsigned int gProgram = 0;
int uColorLocation = -1;
float gRed = 0;
Shader* pShader = nullptr;
Renderer* pRenderer = nullptr;
Texture* pTexture = nullptr;

glm::mat4 gMVP = glm::mat4(1.0f);
glm::vec3 gTranslate(0,0,0);
glm::vec3 gScale(10, 10, 10);
glm::mat4 gProj = glm::ortho<float>(0, 100, 0, 100, -1, 1);
glm::mat4 gViewMatrix = glm::mat4(1.0f);
glm::mat4 gModelMatrix = glm::mat4(1.0f);
glm::mat4 gIdentity = glm::mat4(1.0f);

// imgui
  // Our state
bool show_demo_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);


void Init(GLFWwindow* window) {

	float positions[] = {
		-0.5f,-0.5f,	0,   0,1,
		0.5f,-0.5f,		0,   1,1,
		0.5f,0.5f,		0,   1,0,
		-0.5f,0.5f,     0,   0,0,
	};
	unsigned int indices[] = { 0,1,2,0,2,3 };

	pVa = new VertexArray();
	pVb = new VertexBuffer(positions, sizeof(positions));
	VertexBufferLayout layout;
	layout.PushFloat(3); // pos:x y z
	layout.PushFloat(2); // uv: x y
	pVa->AddBuffer(*pVb, layout);

	// ibo
	pIB = new IndexBuffer(indices, sizeof(indices) / sizeof(indices[0]));
	pIB->Bind();

	pShader = new Shader("assets/shaders/hello.vs", "assets/shaders/hello.fs");
	pShader->Bind();

	pVa->Unbind();
	pShader->Unbind();

	// GL_ARRAY_BUFFER 和 GL_ELEMENT_ARRAY_BUFFER 的绑定点都会存在 vao 中
	pRenderer = new Renderer();
	pTexture = new Texture("assets/textures/icon.png");

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC1_ALPHA);
	
	//glm::mat4 s = glm::scale(glm::mat4(1.0f), glm::vec3(10, 10, 1));
	//glm::mat4 t = glm::translate(glm::mat4(1), gTranslate);
	//auto modelMatrix = t * s;

	// 设置 imgui
	IMGUI_CHECKVERSION();
	ImGui::CreateContext();
	ImGuiIO& io = ImGui::GetIO(); (void)io;

	//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;     // Enable Keyboard Controls
	//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;      // Enable Gamepad Controls

	// Setup Dear ImGui style
	ImGui::StyleColorsDark();
	//ImGui::StyleColorsClassic();

	// Setup Platform/Renderer backends
	ImGui_ImplGlfw_InitForOpenGL(window, true);
	ImGui_ImplOpenGL3_Init("#version 330");
}

void Display(GLFWwindow* window) {
	gRed += 0.01f;
	if (gRed > 1) {
		gRed -= 1;
	}

	pRenderer->Clear();

	//imgui
	// Start the Dear ImGui frame
	ImGui_ImplOpenGL3_NewFrame();
	ImGui_ImplGlfw_NewFrame();
	ImGui::NewFrame();

	pShader->Bind();
	// pShader->SetUniform4f("uColor", gRed, 0, 0, 1);
	pTexture->Bind(0);
	pShader->SetUniform1i("uTexture0", 0);

	// 更新mvp
	gModelMatrix = glm::scale(gIdentity, gScale);
	 gModelMatrix = glm::translate(gModelMatrix, gTranslate);
	
	gMVP = gProj * gViewMatrix * gModelMatrix;
	pShader->SetUniformMatrix4("uMVP", gMVP);
	pRenderer->Draw(*pShader, *pVa, *pIB);

	// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
	/*if (show_demo_window)
		ImGui::ShowDemoWindow(&show_demo_window);*/

	// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
	{
		//static float f = 0.0f;
		//static int counter = 0;

		ImGui::Begin("Hello Translation");                          // Create a window called "Hello, world!" and append into it.

		ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
		//ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
		//ImGui::Checkbox("Another Window", &show_another_window);

		ImGui::SliderFloat3("translation", &gTranslate.x, 0.0f, 10.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
		//ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color

		//if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
		//	counter++;
		//ImGui::SameLine();
		//ImGui::Text("counter = %d", counter);

		ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
		ImGui::End();
	}


	// imgui renderer
	 // Rendering
	ImGui::Render();
	int display_w, display_h;
	glfwGetFramebufferSize(window, &display_w, &display_h);
	glViewport(0, 0, display_w, display_h);
	//glClearColor(0, 0, 0, 1);
	//glClear(GL_COLOR_BUFFER_BIT);
	ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
	
}


void CleanUp(GLFWwindow* window) {
	// imgui Cleanup
	ImGui_ImplOpenGL3_Shutdown();
	ImGui_ImplGlfw_Shutdown();
	ImGui::DestroyContext();
}

int main(void)
{
	GLFWwindow* window;

	/* Initialize the library */
	if (!glfwInit())
		return -1;


	//  使用 core profile.
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	/* Make the window's context current */
	glfwMakeContextCurrent(window);


	// init glew
	// glew 按 静态库 使用
	// 需要 #define GLEW_STATIC
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		/* Problem: glewInit failed, something is seriously wrong. */
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
	}

	// 打印 版本
	cout << "gl version:" << glGetString(GL_VERSION) << endl;

#pragma region 初始化

	Init(window);

#pragma endregion


	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
#pragma region 绘制
		Display(window);
#pragma endregion

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();
	}

#pragma region 清理工作
	CleanUp(window);
#pragma endregion

	glfwTerminate();
	return 0;
}